using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;
using MCGameEngine.Animations;

namespace MCGameEngine.Physic_Layer
{
    class PhysicLayer : Microsoft.Xna.Framework.GameComponent
    {
        private int index=0;

        private Dictionary<string, BasicObject> elements;
        private List<PhysicObject> collisionList;

        public PhysicLayer(MyGame game): base(game)
        {
            elements = new Dictionary<string, BasicObject>();
            collisionList = new List<PhysicObject>();
        }

        public void Add(BasicObject bo)
        {
            elements.Add("unnamed" + index, bo);
            index++;

            PhysicObject po = bo as PhysicObject;
            if (po != null)
            {
                collisionList.Add(po);
            }
        }

        public void Add(BasicObject bo, string name)
        {
            elements.Add(name,bo);

            PhysicObject po = bo as PhysicObject;
            if (po != null)
            {
                collisionList.Add(po);
            }
        }

        public Dictionary<string, BasicObject>.ValueCollection All()
        {
            return elements.Values;
        }

        public BasicObject Element(string name)
        {
            try
            {
                return elements[name];
            }
            catch
            {
                return null;
            }
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public void Draw()
        {
            foreach (BasicObject bo in elements.Values)
            {
                bo.Draw(((MyGame)this.Game).camera);
            }
        }


        public override void Update(GameTime gameTime)
        {
            foreach (BasicObject bo in elements.Values)
            {
                bo.Update(gameTime);
            }

            foreach (PhysicObject po in collisionList)
            {
                if (po.Velocity.Length()!=0)
                {
                    foreach (BasicObject bo in elements.Values)
                    {
                        if (po.collision_sphere != null && bo.collision_sphere != null)
                        {
                            if (po.collision_sphere.Collide(bo.collision_sphere))
                            {
                                ((MyGame)this.Game).OnObjectCollision(po, bo);
                            }
                        }
                    }
                }
            }
            base.Update(gameTime);
        }
    }
}